package com.chen.authority.common.util;

import cn.hutool.http.Header;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 请求工具类
 *
 * @author chengy
 * @date 2022/11/04
 */
public class RequestUtil {

    /**
     * 获取当前请求
     *
     * @return 请求
     */
    public static HttpServletRequest getRequest() {
        return (HttpServletRequest) Objects
                .requireNonNull(RequestContextHolder.getRequestAttributes())
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
    }

    /**
     * 判断是否为爬虫
     *
     * @param request 请求
     * @return 是否为爬虫
     */
    public static boolean isReptile(HttpServletRequest request) {
        String userAgent = request.getHeader(Header.USER_AGENT.toString());
        String referer = request.getHeader(Header.REFERER.getValue());
        // ua校验
        if (Objects.isNull(userAgent) || !userAgent.contains("Mozilla")) {
            return true;
        }
        // 防盗链校验 todo 部署时换成真实的线上地址
        return Objects.isNull(referer) || !referer.startsWith("http://localhost");
    }

}